import { Util } from "./util.js";

class PuzzleArray {
  // 拼图难度
  constructor(level) {
    this.level = level;
    this._initPuzzleArray();
  }
  //是否拼图成功
  isSuccess() {
    for (let i = 0; i < this.t2fArr.length; i++) {
      for (let j = 0; j < this.t2fArr[i].length; j++) {
        if (this.t2fArr[i][j][0] !== i || this.t2fArr[i][j][1] !== j) {
          return false;
        }
      }
    }
    return true;
  }
  // 交换两拼图位置
  swap(e1Rx, e1Ry, e2Rx, e2Ry) {
    // e1的位置
    let e1 = this.t2fArr[e1Rx][e1Ry];
    // e2的位置
    let e2 = this.t2fArr[e2Rx][e2Ry];
    this.t2fArr[e1Rx][e1Ry] = e2;
    this.t2fArr[e2Rx][e2Ry] = e1;

    this.f2tArr[e1[0]][e1[1]] = [e2Rx, e2Ry];
    this.f2tArr[e2[0]][e2[1]] = [e1Rx, e1Ry];
  }
  // 初始化拼图数组
  _initPuzzleArray() {
    let level = this.level;
    //放在x,y位置的元素编号是多少
    this.f2tArr = new Array(level);
    //编号为x,y的元素放在哪个位置上
    this.t2fArr = new Array(level);
    // 初始化位置
    for (let i = 0; i < level; i++) {
      this.t2fArr[i] = new Array(level);
      this.f2tArr[i] = new Array(level);
      for (let j = 0; j < level; j++) {
        this.t2fArr[i][j] = [i, j];
        this.f2tArr[i][j] = [i, j];
      }
    }
    this._randomize();
  }
  // 随机化数组位置
  _randomize() {
    for (let i = 0; i < 100 * this.level; i++) {
      this._randomizePositionOnce(
        ...this.t2fArr[this.level - 1][this.level - 1]
      );
    }
  }
  //将x,y坐标处的点随机与其上下左右中的一个点互换位置
  _randomizePositionOnce(x, y) {
    // 可选换位的方向
    // 0123 上右下左
    let choose = [];
    if (x > 0) {
      choose.push(0);
    }
    if (y > 0) {
      choose.push(3);
    }
    if (x < this.level - 1) {
      choose.push(2);
    }
    if (y < this.level - 1) {
      choose.push(1);
    }
    // 换位对象的实际坐标
    let rx, ry;
    switch (Util.randomChoose(choose)) {
      case 0:
        [rx, ry] = this.f2tArr[x - 1][y];
        break;
      case 1:
        [rx, ry] = this.f2tArr[x][y + 1];
        break;
      case 2:
        [rx, ry] = this.f2tArr[x + 1][y];
        break;
      case 3:
        [rx, ry] = this.f2tArr[x][y - 1];
        break;
      default:
        return;
    }
    //换位置
    this.t2fArr[this.level - 1][this.level - 1] = this.t2fArr[rx][ry];

    this.f2tArr[this.t2fArr[rx][ry][0]][this.t2fArr[rx][ry][1]] = [
      this.level - 1,
      this.level - 1,
    ];

    this.t2fArr[rx][ry] = [x, y];

    this.f2tArr[x][y] = [rx, ry];
  }
}

export { PuzzleArray };
